package com.gz.servlet;

import com.gz.utils.WebUtils;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet(urlPatterns = "/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //文件上传
        //1.判断是不是文件表单
        if(ServletFileUpload.isMultipartContent(request)){
            //2.创建DiskFileItemFactory对象，用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            /*
             * <input type="file" name="pic" id="" value="" onchange="prev(this)"/>
             *     家居名: <input type="text" name="name"><br/>
             *     <input type="submit" value="上传"/>
             */
            //3.创建一个解析上传数据的工具对象
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //解决接收到的文件名是中文的乱码问题
            servletFileUpload.setHeaderEncoding("UTF-8");

            //4.关键地方，servletFileUpload 把表单提交给text文件
              //将其封装到FileItem文件中
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                System.out.println("fileItems= "+fileItems);
                //fileItems= [name=4.png, StoreLocation=E:\Java\copy\apache-tomcat-9.0.99\temp\
                // upload_ad75d225_2746_4d93_9e1b_f85fc294eb48_00000000.tmp, size=158847 bytes,
                // isFormField=false, FieldName=pic, name=null, StoreLocation=null, size=0 bytes,
                // isFormField=true, FieldName=name]
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//如果是true就是文本 input text
                        String name = fileItem.getString("UTF-8");
                        System.out.println("家具名="+name);
                    }else { //是一个文件
                        //获取上传文件的名字
                        String name = fileItem.getName();
                        System.out.println("上传的文件名= "+name);


                        //将temp下的文件保存到你指定的目录
                        //1.指定一个目录
                        String filepath="/upload/";
                        //获取完整目录
                        String realPath = request.getServletContext().getRealPath(filepath);
                        //realPath= E:\Java\java_code\JavaWeb\java-web\fileupdown\target\jsp\ upload\
                        System.out.println("realPath= "+realPath);
                        //创建这个上传的目录
                        //因为大部分文件不要保存到同一个文件，否则装不下
                        //所以做一个工具类来获得年月日，每次保存文件将文件名创建为路径+年月日(创建文件的日期)
                        String date=WebUtils.getYearMonthDay();
                        //为了防止文件名重复，可以添加前缀，保证唯一性
                        name= UUID.randomUUID()+"_"+System.currentTimeMillis()+"_"+name;
                        File fileRealPathDirectory = new File(realPath+"/"+date);
                        if(!fileRealPathDirectory.exists()){
                            fileRealPathDirectory.mkdirs();
                        }
                        //4.将文件拷贝到fileRealPathDirectory
                        //目录加文件名
                        String fileFullPath=fileRealPathDirectory+"/"+name;
                        fileItem.write(new File(fileFullPath));

                        //提示信息
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().write("上传成功~");
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
}
